package chat.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import javax.swing.JOptionPane;

public class MessageSender implements Runnable
{

    SocketChannel client = ChatClientUI.client;

    String msg;

    public MessageSender(String msg)
    {
        this.msg = msg;
        new Thread(this).start();
    }

    @Override
    public void run()
    {
        try
        {
            writeToChannel(msg);
        }
        catch (IOException e)
        {
            // handle io exception
            System.out.println("Failed to connect to chat server:" + e);
        }

    }

    private void writeToChannel(String msg) throws IOException
    {
        ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
        if (client.isConnected())
        {
            client.write(buffer);
        }

    }

}
